二分查找Java实现

这个栗子是用Java实现的二分查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BinarySearch {

public static int binarySearch(int array[], int number, int value) {
int left = 0;
int right = number - 1;
while (left <= right) {
int middle = left + ((right - left) >> 1);
if (array[middle] > value) {
right = middle - 1;
} else if (array[middle] < value) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
}